<template>
    <view class="live-page">
        <uni-nav-bar dark fixed shadow background-color="#667eea" status-bar left-icon="settings" title="直播"
            @clickLeft="handleSetting" />

        <search-date @search="handleSearch" @dateChange="handleDateChange" :showDate="false" />
        <!-- <view class="tab-section">
            <view @click="tab(1)" class="tab-item" :class="tabIndex == 1 ? 'tab-active' : ''">
                <text class="tab-text">直播中</text>
                <view class="tab-indicator" v-if="tabIndex == 1"></view>
            </view>
            <view @click="tab(0)" class="tab-item" :class="tabIndex == 0 ? 'tab-active' : ''">
                <text class="tab-text">未开始</text>
                <view class="tab-indicator" v-if="tabIndex == 0"></view>
            </view>
        </view> -->
        <!-- 直播列表 -->
        <scroll-view style="height: 100vh" scroll-y refresher-enabled @scrolltolower="loadMore">
            <view class="live-list">
                <view v-for="item in liveList" :key="item.id" class="live-card" @click="toLiveDetail(item.id)">
                    <!-- 封面 -->
                    <view class="cover-box">
                        <image class="cover" :src="item.cover_image" mode="aspectFill" />
                        <!-- 观看人数 -->
                        <view class="count">
                            <!-- <text>👁</text> -->
                            <uni-icons type="eye" color="#fff" size="14" />
                            <!-- <text>{{ formatCount(item.online) }}</text> -->
                            <text>{{ formatCount(Math.random() * 100000) }}</text>
                        </view>
                        <!-- 直播中 -->
                        <view v-if="item.liveState === 1" class="live-badge">{{ '直播中' }}</view>
                        <view v-else-if="item.liveState === 0" class="un-start">{{ '未开始' }}</view>
                        <view v-else class="finally">{{ item.stateText }}</view>
                    </view>

                    <!-- 下方信息 -->
                    <view class="info">
                        <text class="title">{{ item.title }}</text>
                        <view class="up-row">
                            <!-- <image class="face" :src="item.headPortraitUri" />
                            <text class="up-name">{{ item.speaker }}</text> -->
                            <text class="time">{{ item.startTime }}</text>
                        </view>
                        <view class="tag-row">
                            <text class="tag">{{ item.categoryName }}</text>
                        </view>
                        <text class="school">{{ "云南师范大学附属中学" }}</text>
                        <!-- <text class="school">{{ item.schoolName }}</text> -->
                    </view>
                </view>
            </view>
            <uni-load-more :status="moreStatus"></uni-load-more>
        </scroll-view>
        <!-- 弹出-->
        <leftSetting ref="settingRef" />
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import uniReq from '@/api/uniReq';
import leftSetting from '@/components/leftSetting/leftSetting.vue'
import { onPullDownRefresh, onLoad } from '@dcloudio/uni-app';
import searchDate from '@/components/searchDate/searchDate.vue'
import { onShow } from '@dcloudio/uni-app';
import { IMG_API } from '@/utils/auth'

const moreStatus = ref('more')
const settingRef = ref(null)

// 直播状态
const tabIndex = ref(1)
const tab = (index) => {
  tabIndex.value = index
  // 1 直播中  0 未开始  ← 后端字段
  params.value.state = index
  params.value.pageIndex = 1
  liveList.value = []        // 关键：先清空
  moreStatus.value = 'more'
  getLiveList()
}


// 直播列表/分页参数
const liveList = ref([])
const params = ref({
    pageIndex: 1,
    state: 1,
    pageSize: 50,
    devSearchKey: ''
})

// 搜索
const handleSearch = (keyword) => {
    params.value.keyword = keyword
    params.value.pageIndex = 1
    getLiveList()
}
// 日期变化
const handleDateChange = (date) => {
    // params.value.startTimeGe = date
    params.value.pageIndex = 1
    // params.value.keyword = keyword
    getLiveList()
}

// 获取直播列表
const getLiveList = async () => {
    moreStatus.value = 'loading'
    try {
        const res = await uniReq({
            url: '/v3/live/pageWithExt',
            method: 'GET',
            data: params.value
        })
        console.log('直播列表:', res.data.list);
        if (res.code === 0 && res.data.list.length > 0) {
            liveList.value = res.data.list
            if (res.data.total == 0 && res.data.list.length <= res.data.total) {
                moreStatus.value = 'noMore';
                uni.showToast({
                    title: '没有更多了',
                    icon: 'none'
                })
                return
            } else {
                moreStatus.value = 'more'
            }
        } else {
            uni.showToast({
                title: res.msg || '暂无数据',
                icon: 'none'
            })
            moreStatus.value = 'noMore'
        }
    } catch (error) {
        uni.showToast({
            title: error,
            icon: 'none'
        })
        moreStatus.value = 'noMore'
    }
}

// 格式化在线人数
function formatCount(num) {
    return num > 999 ? (num / 10000).toFixed(1) + '万' : num
}

const toLiveDetail = (id) => {
    uni.navigateTo({
        url: '/pages/video/live/liveDetail?id=' + id
    })
}

// onMounted(() => {
//     getLiveList()
// })

// onLoad(() => {
//     getLiveList()
// })

// 或者使用onShow，这样每次页面显示都会刷新数据
onShow(() => {
    getLiveList()
})

// 下拉刷新触发
onPullDownRefresh(async () => {
    console.log('下拉刷新');
    params.value.pageIndex = 1
    try {
        await getLiveList()
        uni.stopPullDownRefresh()
    } catch (error) {
        uni.stopPullDownRefresh() // 即使出错也要停止刷新
    }
})

const loadMore = async () => {
    console.log('加载更多');
    params.value.pageIndex++
    moreStatus.value = 'loading'
    const res = await uniReq({
        url: '/live/listLive',
        method: 'GET',
        data: params.value
    })
    if (res.code === 200 && res.data.records.length > 0) {
        liveList.value = [...liveList.value, ...res.data.records]
        moreStatus.value = 'more'
    } else {
        uni.showToast({
            title: '没有更多了',
            icon: 'none'
        })
        moreStatus.value = 'noMore'
    }
}

const handleSetting = () => {
    settingRef.value.open()
}
</script>

<style lang="scss" scoped>
.live-page {
    padding: 20rpx 10rpx;
    padding-top: 0;
    background: #f5f5f5;
    min-height: 100vh;

    .tab-section {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 68rpx;
        margin-bottom: 10rpx;
        background: #fff;
        border-bottom: 1rpx solid #f5f5f5;

        .tab-item {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            position: relative;
            transition: all 0.2s;

            .tab-text {
                font-size: 30rpx;
                color: #666;
            }

            // 激活态
            &.tab-active {
                .tab-text {
                    color: #007aff;
                    font-weight: 600;
                }
            }
        }

        // 底部指示条
        .tab-indicator {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60rpx;
            height: 4rpx;
            background: #007aff;
            border-radius: 2rpx;
        }
    }
}

/* 两列瀑布流 */
.live-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.live-card {
    width: 48%;
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
}

/* 封面区域 */
.cover-box {
    position: relative;

    .cover {
        width: 100%;
        height: 200rpx;
    }

    .count {
        position: absolute;
        left: 10rpx;
        bottom: 10rpx;
        display: flex;
        align-items: center;
        font-size: 22rpx;
        color: #fff;
        background: rgba(0, 0, 0, 0.4);
        padding: 4rpx 10rpx;
        border-radius: 20rpx;

        .iconfont {
            font-size: 22rpx;
            margin-right: 6rpx;
        }
    }

    .live-badge {
        position: absolute;
        right: 10rpx;
        top: 10rpx;
        background: #21ff76ad;
        color: #fff;
        font-size: 20rpx;
        padding: 4rpx 10rpx;
        border-radius: 20rpx;
    }

    .un-start {
        position: absolute;
        right: 10rpx;
        top: 10rpx;
        background: #2189ff;
        color: #fff;
        font-size: 20rpx;
        padding: 4rpx 10rpx;
        border-radius: 20rpx;
    }

    .finally {
        position: absolute;
        right: 10rpx;
        top: 10rpx;
        background: #888;
        color: #fff;
        font-size: 20rpx;
        padding: 4rpx 10rpx;
        border-radius: 20rpx;
    }
}

/* 信息区 */
.info {
    padding: 12rpx;

    .title {
        font-size: 28rpx;
        color: #333;
        line-height: 40rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
    }

    .up-row {
        display: flex;
        align-items: center;
        margin-top: 10rpx;

        .face {
            width: 32rpx;
            height: 32rpx;
            border-radius: 50%;
            margin-right: 8rpx;
        }

        .up-name {
            font-size: 24rpx;
            color: #666;
        }

        .time {
            font-size: 22rpx;
            color: #666;
            // margin-left: 8rpx;
        }
    }

    .tag-row {
        margin-top: 8rpx;

        .tag {
            display: inline-block;
            font-size: 22rpx;
            color: #2189ff;
            background: #e6f2ff;
            padding: 4rpx 10rpx;
            border-radius: 10rpx;
        }
    }

    .school {
        font-size: 22rpx;
        color: #666;
    }
}

:deep(.uni-navbar__header-btns-left) {
    width: 60rpx !important;
}
</style>